<template>
    <div class="scienceshotsStatic_N_box">
        <div class="theme_tool_btn">
            <div class="btn-wrap">
                <span class="tool-label">标注标绘：</span>

                <span
                    class="color_block"
                    @click="disAllColor('drawColor')"
                    :style="{ backgroundColor: drawColor }"
                ></span>
                <div class="choice_box" v-show="disDrawColor">
                    <span v-for="(item, index) in allColor" :key="index">
                        <span
                            @click="changeColor('drawColor', item, index)"
                            class="ele_color"
                            v-if="item !== drawColor"
                            :style="{ backgroundColor: item }"
                        ></span>
                    </span>
                </div>

                <img
                    v-for="(item, index) in headerBtn.drawBtn"
                    :key="index"
                    @click="changeTools(item, 'clickPng1')"
                    class="fun-btn"
                    :src="
                        clickPng1 === item.toolTitle || mouseroverPng1 === item.toolTitle
                            ? item.hoverUrl
                            : item.imgUrl
                    "
                    @mouseover="overFun(0, item.toolTitle, 'mouseroverPng1')"
                    @mouseout="overFun(1, item.toolTitle, 'mouseroverPng1')"
                />
            </div>
            <div class="btn-wrap">
                <span class="tool-label">经纬网：</span>
                <img
                    v-for="(item, index) in headerBtn.graticules"
                    :key="index"
                    @click="changeTools(item, 'clickPng2')"
                    class="fun-btn"
                    :src="
                        clickPng2 === item.toolTitle || mouseroverPng2 === item.toolTitle
                            ? item.hoverUrl
                            : item.imgUrl
                    "
                    @mouseover="overFun(0, item.toolTitle, 'mouseroverPng2')"
                    @mouseout="overFun(1, item.toolTitle, 'mouseroverPng2')"
                />
            </div>
            <div class="btn-wrap">
                <span class="tool-label">统计：</span>
                <img
                    v-for="(item, index) in headerBtn.statistics"
                    :key="index"
                    @click="changeTools(item, 'clickPng3')"
                    class="fun-btn"
                    :src="
                        clickPng3 === item.toolTitle || mouseroverPng3 === item.toolTitle
                            ? item.hoverUrl
                            : item.imgUrl
                    "
                    @mouseover="overFun(0, item.toolTitle, 'mouseroverPng3')"
                    @mouseout="overFun(1, item.toolTitle, 'mouseroverPng3')"
                />
            </div>
            <div v-if="isShowGray" class="colorCtrlTool">
                <span></span>
                <span>起始渐变色：</span>
                <div class="color_choice">
                    <span
                        class="color_block"
                        @click="disAllColor('startColor')"
                        :style="{ backgroundColor: startColor }"
                    ></span>
                    <div class="choice_box" v-show="disStartColor">
                        <span v-for="(item, index) in allColor" :key="index">
                            <span
                                @click="changeColor('startColor', item)"
                                class="ele_color"
                                v-if="item !== startColor && item !== endColor"
                                :style="{ backgroundColor: item }"
                            ></span>
                        </span>
                    </div>
                </div>
                <span>终止渐变色：</span>
                <div class="color_choice">
                    <span
                        class="color_block"
                        @click="disAllColor('endColor')"
                        :style="{ backgroundColor: endColor }"
                    ></span>
                    <div class="choice_box" v-show="disEndColor">
                        <span v-for="(item, index) in allColor" :key="index">
                            <span
                                @click="changeColor('endColor', item)"
                                class="ele_color"
                                v-show="item !== startColor && item !== endColor"
                                :style="{ backgroundColor: item }"
                            ></span>
                        </span>
                    </div>
                </div>
            </div>
            <!-- <div class="button_box">
                <span
                    @click="chartsShow"
                    style="padding:4px 10px"
                    class="public_btn"
                    ><img
                        src="./theme/img/download.png"
                        class="btn-icon"
                    />下载</span
                >
            </div> -->
            <div class="button_box">
                <span @click="exportImg" style="padding:4px 10px" class="public_btn">
                    <img src="./theme/img/export.png" class="btn-icon" />
                    导出
                </span>
            </div>
        </div>
        <div class="science_box">
            <div class="header_class">
                <input type="text" v-model="title" class="title_inp" maxlength="28" />
                <div class="time_inf">
                    <el-dropdown :hide-on-click="false" @command="changeTime">
                        <span class="el-dropdown-link">{{ timeString }}(北京时间)</span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="(item, i) in timeArr" :key="i" :command="i">
                                {{ item }}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>
            <div
                class="content_class"
                :class="{ visibilityScreen: isShowScreenshots }"
                id="contentId"
            >
                <img class="mapImg" v-if="mapImg" :src="mapImg" />
                <canvas
                    class="img_latLng_inf"
                    :width="canvasWidth + 'px'"
                    :height="canvasHeight + 'px'"
                    id="themetic-canvas"
                ></canvas>
                <HeatmapDom
                    v-if="isShowGray && isShowByHeatmap"
                    :beginColor="startColor"
                    :endColor="endColor"
                    :time="time"
                    :geo="heatMapGeo"
                    :type="mapType"
                    @initLegend="initLegend"
                    ref="HeatmapDom"
                ></HeatmapDom>
                <MeshFill
                    v-if="isShowGray && !isShowByHeatmap"
                    :beginColor="startColor"
                    :endColor="endColor"
                    :time="time"
                    :geo="heatMapGeo"
                    :type="mapType"
                    @initLegend="initLegend"
                    ref="MeshFill"
                ></MeshFill>
            </div>
            <LegendPanel ref="legendPanel"></LegendPanel>
            <Bottom :point="point" v-show="isBottomShow"></Bottom>
            <div class="charts" :class="[$route.query.nowChoice === 'REF' ? 'right' : 'middle']">
                <GrayLevelCharts :id="charts_id" v-show="isPieShow"></GrayLevelCharts>
            </div>
            <div class="pie-container">
                <Pie v-if="isPieShow" :grayArr="grayArr"></Pie>
            </div>
        </div>
    </div>
</template>

<script>
/* global Cesium viewer */
import ThematicJs from 'U/thematic.js';
import DrawGraph from 'U/drawGraph.js';
import HeatmapDom from '../heatmap';
import MeshFill from '../meshFill';
import Bottom from './bottom';
import LegendPanel from './legendPanel';
import Canvas2Image from 'U/canvas2image.js';
import { joinWkt } from 'U/dataQueryFunc';
import {
    // antiShake,
    throttle,
} from 'U/serviceOptimize.js';
import { changeClockTime } from 'U/imageryLayerFun';
import GrayLevelCharts from './grayLevelCharts.vue';
import Pie from './3dPie.vue';
import Canvg from 'canvg';
export default {
    name: 'scienceshotsStatic-N',
    components: {
        HeatmapDom,
        Bottom,
        LegendPanel,
        MeshFill,
        GrayLevelCharts,
        Pie,
    },
    data() {
        return {
            clickPng1: '',
            mouseroverPng1: '',
            clickPng2: 'graticules',
            mouseroverPng2: '',
            clickPng3: '',
            mouseroverPng3: '',
            headerBtn: {
                drawBtn: [
                    {
                        imgUrl: require('./theme/img/arrow0.png'),
                        hoverUrl: require('./theme/img/arrow1.png'),
                        toolTitle: 'draw_arrow',
                        fun_draw_arrow: 'drawArrow',
                    },
                    {
                        imgUrl: require('./theme/img/rectangular0.png'),
                        hoverUrl: require('./theme/img/rectangular1.png'),
                        toolTitle: 'draw_rectangular',
                        fun_draw_rectangular: 'drawRectangular',
                    },
                    {
                        imgUrl: require('./theme/img/round0.png'),
                        hoverUrl: require('./theme/img/round1.png'),
                        toolTitle: 'draw_round',
                        fun_draw_round: 'drawRound',
                    },
                    {
                        imgUrl: require('./theme/img/polygon0.png'),
                        hoverUrl: require('./theme/img/polygon1.png'),
                        toolTitle: 'draw_polygon',
                        fun_draw_polygon: 'drawPolygon',
                    },
                    {
                        imgUrl: require('./theme/img/font0.png'),
                        hoverUrl: require('./theme/img/font1.png'),
                        toolTitle: 'draw_font',
                        fun_draw_font: 'drawFont',
                    },
                    {
                        imgUrl: require('./theme/img/clear0.png'),
                        hoverUrl: require('./theme/img/clear1.png'),
                        toolTitle: 'draw_clear',
                        fun_draw_clear: 'clearDraw',
                    },
                ],
                statistics: [
                    {
                        imgUrl: require('./theme/img/statistics0.png'),
                        hoverUrl: require('./theme/img/statistics1.png'),
                        toolTitle: 'statistics',
                        fun_statistics: 'chartsShow',
                    },
                ],
                graticules: [
                    {
                        imgUrl: require('./theme/img/graticules0.png'),
                        hoverUrl: require('./theme/img/graticules1.png'),
                        toolTitle: 'graticules',
                        fun_graticules: 'latLngLine',
                    },
                ],
            },
            mouseDownLCode: false,
            mouseDownRCode: false,
            canvasPadding: 30,
            isDisLngLatLine: true, // 是否展示经纬度辅助线
            drawTool: null, // 选择绘制的形状
            heatMapIndex: 0,
            isShowScreenshots: false,
            drawColor: 'rgb(0,0,0)',

            startColor: 'rgb(255,255,255)',
            endColor: 'rgb(0,0,0)',
            allColor: [
                'rgb(0,0,0)',
                'rgb(255,255,255)',
                'rgb(0,255,0)',
                'rgb(255,0,0)',
                'rgb(255,165,0)',
                'rgb(255,127,80)',
                'rgb(255,255,0)',
                'rgb(0,255,255)',
                'rgb(255,0,255)',
            ],
            disDrawColor: false,
            disStartColor: false, // 开始颜色
            disEndColor: false, // 结束颜色
            mapType: '',
            timeString: '',
            timeArr: '',
            time: {
                year: '',
                month: '',
                date: '',
                hour: '',
            },
            title: '',
            mapImg: null, // 地图中心的截图
            themeticWidth: '800', // 中心canvas宽度
            topOrBottonH: '170', // 专题图上面或下面区域的高度
            canvasWidth: '738',
            canvasHeight: '570',
            heatMapGeo: '', // heatmap的经纬度范围
            isShowByHeatmap: false, // 是否采用heatMap形式展示
            currentIndex: '',
            charts_id: 'test',
            isPieShow: false,
            grayArr: [17, 51.7, 22.8, 8.5],
            isShowGray: true, // 是否进行灰度值渲染
            point: [],
            isBottomShow: false,
        };
    },
    mounted() {
        // 初始化专题图js
        this.thematicJs = new ThematicJs({
            borderDis: this.canvasPadding,
            Canvas: document.getElementById('themetic-canvas'),
            lineIsExist: false,
        });
        // 初始化绘制
        this.drawGraph = new DrawGraph({
            borderDis: this.canvasPadding,
            contentName: 'contentId',
            allColor: this.allColor,
            beginColor: this.drawColor,
        });
        this.isShowGray = this.$route.query.nowChoice !== 'REF';
    },
    methods: {
        overFun(numCode, title, name) {
            if (numCode === 0) {
                this[name] = title;
            } else {
                this[name] = null;
            }
        },
        changeTools(item, name) {
            this[item['fun_' + item.toolTitle]]();
            if (name !== 'clickPng1') {
                this[name] = this[name] ? '' : item.toolTitle;
            } else {
                this[name] = item.toolTitle;
            }
        },
        hideModel() {
            console.log('关闭');
        },
        // 初始加载经纬度线
        initLatLng() {
            this.mapListener();
            this.isShowScreenshots = true;
            throttle(this.toLatLngBox).apply(this);
            // this.calculateHeight();
        },
        // 初始化热力图
        initHotMap() {
            // 热力图
            if (this.isShowGray && this.isShowByHeatmap) {
                this.$refs.HeatmapDom.setBoxWH({
                    borderDis: this.canvasPadding,
                    contentName: 'contentId',
                });
            }
            // 网格图
            if (this.isShowGray && !this.isShowByHeatmap) {
                this.$refs.MeshFill.setBoxWH({
                    borderDis: this.canvasPadding,
                    contentName: 'contentId',
                });
            }
        },
        // 计算canvas容器的高度
        calculateHeight() {
            let canvasHeight = Math.abs(
                Number(this.themeticWidth - 4 * this.canvasPadding) / this.aspectRatio
            );
            // 专题图的高
            let themeticHeight = canvasHeight + 2 * this.canvasPadding + 2 * this.topOrBottonH;
            // canvas的高宽
            this.canvasHeight = canvasHeight;
            this.canvasWidth = this.themeticWidth - 2 * this.canvasPadding;
            this.$nextTick(() => {
                let thematicMapBox = document.getElementsByClassName('thematicMap_box')[0];
                thematicMapBox.style.setProperty('--thematicWidth', `${this.themeticWidth}px`);
                thematicMapBox.style.setProperty('--thematicHeight', `${themeticHeight}px`);
                thematicMapBox.style.setProperty(
                    '--thematicImgWDis',
                    `${2 * this.canvasPadding}px`
                );
                thematicMapBox.style.setProperty('--thematicImgHDis', `${this.topOrBottonH}px`);
            });
        },
        // 构建图例
        initLegend(max, min) {
            let obj = {
                startColor: this.startColor,
                endColor: this.endColor,
                max: max,
                min: min,
            };
            console.log(obj);
            this.$refs.legendPanel.changeLegend(obj);
        },
        mapListener() {
            let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            // 鼠标滚轴转动
            handler.setInputAction(throttle(this.toLatLngBox), Cesium.ScreenSpaceEventType.WHEEL);

            // 鼠标左键按下
            handler.setInputAction(() => {
                // 计算专题图框左上角像素坐标
                this.mouseDownLCode = true;
            }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

            // 鼠标左键抬起
            handler.setInputAction(() => {
                this.mouseDownLCode = false;
            }, Cesium.ScreenSpaceEventType.LEFT_UP);

            // 鼠标右键按下
            handler.setInputAction(() => {
                // 计算专题图框左上角像素坐标
                this.mouseDownRCode = true;
            }, Cesium.ScreenSpaceEventType.RIGHT_DOWN);
            // 鼠标右键抬起
            handler.setInputAction(() => {
                // 计算专题图框左上角像素坐标
                this.mouseDownRCode = false;
            }, Cesium.ScreenSpaceEventType.RIGHT_UP);

            // 鼠标拖动
            // handler.setInputAction(() => {
            //     if (this.mouseDownLCode || this.mouseDownRCode) {
            //         antiShake(this.toLatLngBox).apply(this);
            //     }
            // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            handler.setInputAction(
                throttle(() => {
                    if (this.mouseDownLCode || this.mouseDownRCode) {
                        this.toLatLngBox();
                    }
                }),
                Cesium.ScreenSpaceEventType.MOUSE_MOVE
            );
        },
        // 鼠标动作监听转化为经纬度坐标
        toLatLngBox() {
            let xCode = $('.img_latLng_inf')?.offset().left + this.canvasPadding;
            let yCode = $('.img_latLng_inf')?.offset().top + this.canvasPadding;

            let botX = xCode + $('.img_latLng_inf').width() - 2 * this.canvasPadding;
            let botY = yCode + $('.img_latLng_inf').height() - 2 * this.canvasPadding;

            let leftTopPoin = this.pointToLatLngs([xCode, yCode]);
            let rightBotPoin = this.pointToLatLngs([botX, botY]);

            let points = [
                {
                    lng: leftTopPoin.lng,
                    lat: leftTopPoin.lat,
                },
                {
                    lng: rightBotPoin.lng,
                    lat: leftTopPoin.lat,
                },
                {
                    lng: rightBotPoin.lng,
                    lat: rightBotPoin.lat,
                },
                {
                    lng: leftTopPoin.lng,
                    lat: rightBotPoin.lat,
                },
                {
                    lng: leftTopPoin.lng,
                    lat: leftTopPoin.lat,
                },
            ];
            this.point = [points[1], points[2]];
            this.heatMapGeo = joinWkt(points);
            this.initHotMap();
            if (leftTopPoin && rightBotPoin) {
                this.thematicJs.latlngBoxChange([
                    leftTopPoin.lat,
                    rightBotPoin.lng,
                    rightBotPoin.lat,
                    leftTopPoin.lng,
                ]);
            }
        },
        // 像素坐标转经纬度坐标
        pointToLatLngs(pointArrs) {
            try {
                let pick = new Cesium.Cartesian2(pointArrs[0], pointArrs[1]);
                let cartesian = viewer.scene.globe.pick(
                    viewer.camera.getPickRay(pick),
                    viewer.scene
                );
                let cartesian33 = new Cesium.Cartesian3(cartesian.x, cartesian.y, cartesian.z);
                let cartographic = Cesium.Cartographic.fromCartesian(cartesian33);
                let latLngObg = {};
                latLngObg.lat = Cesium.Math.toDegrees(cartographic.latitude);
                latLngObg.lng = Cesium.Math.toDegrees(cartographic.longitude);
                return latLngObg;
            } catch (error) {
                // 只弹出一次
                if (
                    $('.latLng_msg').closest('.el-message-box__wrapper').style?.display ===
                        'none' ||
                    !$('.latLng_msg').innerHTML
                ) {
                    this.$alert('请重新选择经纬度范围', '提示', {
                        confirmButtonText: '确定',
                        customClass: 'latLng_msg',
                        callback: action => {
                            this.thematicJs.delLine();
                        },
                    });
                }
            }
        },
        // 添加还是删除经纬度辅助线
        latLngLine() {
            this.isDisLngLatLine = !this.isDisLngLatLine;
            this.thematicJs.addOrClear(!this.isDisLngLatLine);
        },
        // 绘制箭头
        drawArrow() {
            this.drawTool = 0;
            this.drawGraph.changeType('arrow');
        },
        // 绘制矩形
        drawRectangular() {
            this.drawTool = 1;
            this.drawGraph.changeType('rect');
        },
        // 绘制圆
        drawRound() {
            this.drawTool = 2;
            this.drawGraph.changeType('circle');
        },
        // 绘制多边形
        drawPolygon() {
            this.drawTool = 3;
            this.drawGraph.changeType('polygon');
        },
        // 文字方法
        drawFont() {
            this.drawTool = 4;
            this.drawGraph.changeType('font');
        },
        // 清空绘制
        clearDraw() {
            this.drawTool = null;
            this.drawGraph.clearDraw();
        },

        // 改变颜色
        changeColor(code, color, index) {
            this[code] = color;
            if (code === 'drawColor') {
                this.drawGraph.changeColor(color, index);
            }
            this.disAllColor(code);
        },
        // 展示所有颜色
        disAllColor(code) {
            if (code === 'startColor') {
                this.disStartColor = !this.disStartColor;
            } else if (code === 'endColor') {
                this.disEndColor = !this.disEndColor;
            } else {
                this.disDrawColor = !this.disDrawColor;
            }
        },
        getTitle() {
            this.title = `${this.time.year}年${this.time.month}月${this.time.date}日${this.time.hour}时${this.mapType}灰度图`;
        },
        getTime(timeString = this.timeArr[0]) {
            if (timeString) {
                let timeObj = new Date(timeString);
                this.time = {
                    year: timeObj.getFullYear(),
                    month: timeObj.getMonth() + 1,
                    date: timeObj.getDate(),
                    hour: timeObj.getHours(),
                };
            }
        },
        changeTime(command) {
            this.timeString = this.timeArr[command];
            this.getTime(this.timeArr[command]);
            this.getTitle();
            if (this.$route.query.nowChoice === 'REF') {
                changeClockTime(this.timeArr[command]);
            }

            this.isPieShow = false;
        },
        // 导出
        exportImg() {
            this.svgToCanvas();
        },
        async mapToCanvas() {
            let canvas = await this.thematicJs.tailoringMap('.thematicMap_box');
            let width = canvas.width;
            let height = canvas.height;
            canvas.id = 'self_canvas';
            let img = Canvas2Image.convertToImage(canvas, width, height);
            this.mapImg = img.src;
            this.$nextTick(() => {
                this.thematicJs.exportScreenshot('.science_box', '我是标题', this.clearImg);
            });
        },
        svgToCanvas() {
            // 以下是对svg的处理
            let nodesToRecover = [];
            let nodesToRemove = [];
            let svgElem = $('#contentId').find('svg'); // divReport为需要截取成图片的dom的id
            this.svgElem = svgElem;
            svgElem.each(
                function(index, node) {
                    let parentNode = node.parentNode;
                    let svg = node.outerHTML.trim();

                    let canvas = document.createElement('canvas');
                    canvas.id = 'svgCanvas';
                    let ctx = canvas.getContext('2d');
                    let v = Canvg.fromString(ctx, svg);
                    v.start();
                    if (node.style.position) {
                        canvas.style.position += node.style.position;
                        canvas.style.left += node.style.left;
                        canvas.style.top += node.style.top;
                    }

                    nodesToRecover.push({
                        parent: parentNode,
                        child: node,
                    });
                    parentNode.removeChild(node);

                    nodesToRemove.push({
                        parent: parentNode,
                        child: canvas,
                    });

                    parentNode.appendChild(canvas);
                    this.$nextTick(() => {
                        if (this.$route.query.nowChoice === 'REF') {
                            this.mapToCanvas();
                        } else {
                            this.thematicJs.exportScreenshot(
                                '.science_box',
                                '我是标题',
                                this.clearImg
                            );
                        }
                    });
                }.bind(this)
            );
        },
        clearImg() {
            $('#svgCanvas').remove();
            this.mapImg = null;
            $('#contentId').append(this.svgElem);
        },
        chartsShow() {
            this.isPieShow = !this.isPieShow;
        },
        initTime() {
            console.log(this.$route.query);
            let { startDate, endDate, times, nowChoice, currentIndex } = this.$route.query;
            this.timeArr = JSON.parse(times);
            this.mapType = nowChoice;
            let startTime = new Date(startDate).getTime();
            let endTime = new Date(endDate).getTime();
            let currentDate = this.timeArr[currentIndex];
            if (startDate) {
                this.timeArr = this.timeArr.filter(item => new Date(item).getTime() >= startTime);
            }
            if (endDate) {
                this.timeArr = this.timeArr.filter(item => new Date(item).getTime() <= endTime);
            }
            let currentTime = new Date(currentDate).getTime();
            if (this.timeArr.length > 0) {
                let res = this.timeArr.filter(item => item === currentDate);
                if (res.length === 0) {
                    currentTime < startTime
                        ? this.timeArr.unshift(currentDate)
                        : this.timeArr.push(currentDate);
                }
            }
            this.timeString = currentDate;
            this.getTime(currentDate);
            this.getTitle();
            this.isBottomShow = true;
        },
    },
};
</script>
<style lang="scss">
@import './theme/css/scienceshotsStatic-N.scss';
.title_inp {
    outline: none;
    border: none;
    text-align: center;
    font-size: 32px;
}
.charts {
    position: absolute;
    width: 300px;
    height: 135px;
    bottom: 0px;
    z-index: 3;
}
.middle {
    left: 50%;
    transform: translate(-50%);
}
.right {
    right: 0;
}
.pie-container {
    width: 350px;
    height: 200px;
    position: absolute;
    top: 300px;
    left: 300px;
    z-index: 1;
}
</style>
